package com.dianrui.qiyouriding.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.SPUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dianrui.qiyouriding.Constant;
import com.dianrui.qiyouriding.MyApplication;
import com.dianrui.qiyouriding.R;
import com.dianrui.qiyouriding.adapter.FeedBackAdapter;
import com.dianrui.qiyouriding.adapter.TroubleFeedAdapter;
import com.dianrui.qiyouriding.bean.Data;
import com.dianrui.qiyouriding.bean.Feed;
import com.dianrui.qiyouriding.bean.FeedBackTypeBean;
import com.dianrui.qiyouriding.event.RfreshOrderDetails;
import com.dianrui.qiyouriding.util.BitmapUtils;
import com.dianrui.qiyouriding.util.ConvertUtils;
import com.dianrui.qiyouriding.util.GlideUtil;
import com.dianrui.qiyouriding.util.GsonUtil;
import com.dianrui.qiyouriding.util.JsonUtils;
import com.dianrui.qiyouriding.util.MyUtil;
import com.dianrui.qiyouriding.util.NoDoubleClickUtils;
import com.dianrui.qiyouriding.okhttp.OkHttpRequest;
import com.dianrui.qiyouriding.util.StringUtils;
import com.dianrui.qiyouriding.util.ToastUtil;
import com.dianrui.qiyouriding.util.Url;
import com.dianrui.qiyouriding.view.SpaceItemDecoration;
import com.dianrui.qiyouriding.view.ninegride.NineView;
import com.dianrui.qiyouriding.view.ninegride.RatioImageView;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;

/**
 * 故障反馈
 */
@SuppressWarnings("ALL")
public class TroubleFeedActivity extends BaseActivity implements NineView.NineViewShowCallBack {
    private List<String> imageList = new ArrayList<>();
    private String formId;
    private List<Feed> feedList = new ArrayList<>();
    private List<String> idList = new ArrayList<>();
    private TroubleFeedAdapter troubleFeedAdapter;
    private String mvIds;

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.nine)
    NineView nine;
    @BindView(R.id.input)
    EditText input;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.sub_feedback)
    Button subFeedback;

    @Override
    public int getContentViewId() {
        return R.layout.trouble_feed;
    }

    @Override
    public void initView() {
        customInit(true,R.color.main_color);
        if (getIntent()!=null &&getIntent().getExtras()!=null) {
            Bundle bundle=getIntent().getExtras();
            if (bundle != null) {
                mvIds=bundle.getString("mv_id");
            }
        }
        title.setText(getString(R.string.tourble_title));
        checkLocationPerssions();
        mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        troubleFeedAdapter = new TroubleFeedAdapter(this, feedList);
        mRecyclerView.setAdapter(troubleFeedAdapter);
        mRecyclerView.addItemDecoration(new SpaceItemDecoration(10));//间距
        imageList.add("default");
        nine.maxCount(9).CloseSize(70).isShowCloseButton(true).spacing(3).setNineViewShowCallBack(this).setUrlList(imageList);

        input.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                String text = s.toString();
                if (text.length()>0) {
                    subFeedback.setEnabled(true);
                    subFeedback.setBackgroundResource(R.drawable.blue_gradient);
                }else {
                    subFeedback.setEnabled(false);
                    subFeedback.setBackgroundResource(R.drawable.gray_shape);
                }
            }
        });
        getFeedBackType();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void initData() {}

    //检查是否开启定位权限,有其故意关闭权限进入APP后也要有权限提醒设置
    private void checkLocationPerssions() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                nine.maxCount(9).CloseSize(70).isShowCloseButton(true).spacing(3).setNineViewShowCallBack(this).setUrlList(imageList);
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 1);
            }
        }else {
            nine.maxCount(9).CloseSize(70).isShowCloseButton(true).spacing(3).setNineViewShowCallBack(this).setUrlList(imageList);
        }

    }


    //获得反馈类型
    private void getFeedBackType() {
        OkHttpRequest.getInstance().postRequests(Url.GETFEEDBACKTYPE, "", new OkHttpRequest.XCallBack() {
            @Override
            public void onResponse(String response) {
                if (!StringUtils.isEmpty(response)) {
                    String status = JsonUtils.getJsonStr(response, Constant.STATUS);
                    if (feedList != null) {
                        feedList.clear();
                    }
                    if (Constant.DATASUCCESS.equals(status)) {
                        String data = JsonUtils.getJsonStr(response, "data");
                        if (!StringUtils.isEmpty(data)) {
                            List<Feed> list = JsonUtils.jsonStrToList(data, new TypeToken<ArrayList<Feed>>() {
                            }.getType());
                            if (list != null && list.size() > 0) {
                                feedList.addAll(list);
                                troubleFeedAdapter.setNewData(list);
                            }
                            mRecyclerView.setVisibility(View.VISIBLE);
                        }
                    }
                }else {
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
        troubleFeedAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                feedList.get(position).isChecked = !feedList.get(position).isChecked;
                Feed feed = feedList.get(position);
                formId = feed.getForm_id();
                if (!idList.contains(formId)) {
                    idList.add(formId);
                } else {
                    idList.remove(formId);

                }
                troubleFeedAdapter.notifyDataSetChanged();
            }
        });
    }
    @OnClick({R.id.back, R.id.sub_feedback})
    public void onViewClicked(View view) {
        if (NoDoubleClickUtils.isDoubleClick()) {
            return;
        }
            switch (view.getId()) {
                case R.id.back:
                    finish();
                    break;
                case R.id.sub_feedback:
                    if (StringUtils.isEmpty(input.getText().toString().trim())) {
                        ToastUtil.showToast(getString(R.string.tourble_title1));
                    }else if (StringUtils.isEmpty(formId)) {
                        ToastUtil.showToast(getString(R.string.tourble_title2));
                    }else {
                        report();
                    }
                    break;
                    default:
                        break;
            }

    }

    private void report() {
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < imageList.size(); i++) {
            if (!"default".equals(imageList.get(i))) {
                jsonArray.put(ConvertUtils.bitmapToBase64(BitmapUtils.decodeSampledBitmapFromFile(imageList.get(i), 480, 960)));
            }

        }
        JSONArray jsonArray1 = new JSONArray();
        for (int i = 0; i < idList.size(); i++) {
            jsonArray1.put(idList.get(i));

        }
        showLoadingDialog(getString(R.string.upload_error));
        try {
            JSONObject jsonObject = new JSONObject();
            if (!StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
                jsonObject.put("member_id", SPUtils.getInstance().getString("member_id"));
            }
            jsonObject.put("order_id", mvIds);
            jsonObject.put("content", input.getText().toString().trim());
            jsonObject.put("photo", jsonArray);
            jsonObject.put("form_id", jsonArray1);
            OkHttpRequest.getInstance().postRequests(Url.FEEDBACKS, jsonObject.toString(), new OkHttpRequest.XCallBack() {
                @Override
                public void onResponse(String response) {
                    if (!StringUtils.isEmpty(response)) {
                        try {
                            final JSONObject jsonObject = new JSONObject(response);
                            if (null != jsonObject &&!isFinishing()) {
                                if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                    dismissLoadingDialog();
                                    EventBus.getDefault().post(new RfreshOrderDetails());
                                    ToastUtil.showToast(jsonObject.optString("message"));
                                    finish();
                                } else {
                                    dismissLoadingDialog();
                                    ToastUtil.showToast(jsonObject.optString("message"));
                                }

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void failedRequest(String result) {
                    dismissLoadingDialog();
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDisplayOneImage(RatioImageView imageView, String url, int parentWidth, Context context) {
        if ("default".equals(url)) {
            addImageViewList(GlideUtil.glideLoad(false, imageView, TroubleFeedActivity.this, R.mipmap.add_photo));
        } else {
            imageView.setTag(R.id.glide_tag, url);
            addImageViewList(GlideUtil.downLoader(false, imageView, TroubleFeedActivity.this));
        }
    }

    @Override
    public void onDisplayImage(RatioImageView imageView, RatioImageView closeButton, String url, int parentWidth, Context context) {
        if ("default".equals(url)) {
            addImageViewList(GlideUtil.glideLoad(false, imageView, TroubleFeedActivity.this, R.mipmap.add_photo));
            if (closeButton != null) {
                closeButton.setVisibility(View.GONE);
            }
        } else {
            imageView.setTag(R.id.glide_tag, url);
            addImageViewList(GlideUtil.downLoader(false, imageView, TroubleFeedActivity.this));
            if (closeButton != null) {
                closeButton.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void onClickImage(int position, String url, List<String> urlList, Context context) {
        if ("default".equals(url)) {
            int count = 9;
            if (imageList.size() > 1) {
                count = 9 - imageList.size() + 1;
            }
           MyUtil.createPhotoChooseDialog(0, count, TroubleFeedActivity.this, MyApplication.getFunctionConfig(), new GalleryFinal.OnHanlderResultCallback() {
                @Override
                public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
                    if (resultList == null || resultList.size() == 0) {
                        return;
                    }

                    for (int i = 0; i < imageList.size(); i++) {
                        if ("default".equals(imageList.get(i))) {
                            imageList.remove(i);
                        }
                    }
                    for (int i = 0; i < resultList.size(); i++) {
                        imageList.add(resultList.get(i).getPhotoPath());
                    }
                    if (imageList.size() < 9) {
                        imageList.add("default");
                    }
                    nine.urlList(imageList);

                }

                @Override
                public void onHanlderFailure(int requestCode, String errorMsg) {}
            });
        }else {
            List<String> temp = new ArrayList<>();
            int count = 0;
            for (int i = 0; i < imageList.size(); i++) {
                if (!"default".equals(imageList.get(i))) {
                    temp.add(imageList.get(i));
                } else {
                    count++;
                }
            }
            startActivity(new Intent(TroubleFeedActivity.this, BigImageActivity.class)
                    .putStringArrayListExtra("data", (ArrayList<String>) temp)
                    .putExtra("current", position));
        }
    }

    @Override
    public void onClickImageColse(int position, String url, List<String> urlList, Context context) {
        imageList.remove(position);
        int count = 0;
        for (int i = 0; i < imageList.size(); i++) {
            if ("default".equals(imageList.get(i))) {
                count++;
            }
        }
        if (count == 0) {
            imageList.add("default");
        }

        nine.urlList(imageList);
    }

    @Override
    public void onSamePhotos(List<String> mRejectUrlList) {

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    nine.maxCount(9).CloseSize(70).isShowCloseButton(true).spacing(3).setNineViewShowCallBack(this).setUrlList(imageList);
                }
                break;
            default:
                break;

        }
    }


}
